//
//  RefreshView.m
//  KoreaFlower
//
//  Created by Nicejinux on 12. 12. 23..
//  Copyright (c) 2012년 Nicejinux. All rights reserved.
//

#import "RefreshView.h"
#import <QuartzCore/QuartzCore.h>
#import "ListCommunicator.h"
#import "DBSQLQueries.h"
#import "DBManager.h"
#import "GlobalDefine.h"
#import "UIColor+Hex.h"
#import "LoadingView.h"


@interface RefreshView()

@property (nonatomic, strong)   UILabel                 *refreshLabel;
@property (nonatomic, strong)   UILabel                 *refreshLastUpdateTimeLabel;
@property (nonatomic, strong)   UIImageView             *refreshArrow;
@property (nonatomic, strong)   LoadingView *refreshSpinner;

@property (nonatomic, strong)   UIView                  *refreshFooterView;
@property (nonatomic, strong)   UILabel                 *refreshFooterLabel;
@property (nonatomic, strong)   UIImageView             *refreshFooterArrow;
@property (nonatomic, strong)   UIActivityIndicatorView *refreshFooterSpinner;

@property (nonatomic, assign)   BOOL                    isLoading;

@property (nonatomic, assign)   BOOL                    isNetworkLoading;
@end


@implementation RefreshView
@synthesize refreshHeaderHeight;
//@synthesize refreshHeaderView;
@synthesize refreshLabel;
@synthesize refreshLastUpdateTimeLabel;
@synthesize refreshArrow;
@synthesize refreshSpinner;

@synthesize refreshFooterView;
@synthesize refreshFooterLabel;
@synthesize refreshFooterArrow;
@synthesize refreshFooterSpinner;

@synthesize isLoading;
@synthesize isNetworkLoading;
@synthesize delegate;

@synthesize isRequestCancel;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        refreshHeaderHeight = 60.0f;
        
        [self addPullToRefreshHeader];
    }
    return self;
}


#pragma mark - method
/**
 pull down refresh 기능을 적용시킨다.
 만약 subclass가 pull down refresh 기능이 필요없다면, empty method로 override하면 된다.
 @param
 @returns
 @exception
 */
- (void)addPullToRefreshHeader
{
    self.backgroundColor = [UIColor clearColor];
    
    isRequestCancel = NO;
    
    refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 16, 250, 13)];
    refreshLabel.backgroundColor = [UIColor clearColor];
    refreshLabel.font = [UIFont boldSystemFontOfSize:11];
    refreshLabel.textColor = [UIColor colorWithHex:0x3a3333];
    refreshLabel.shadowColor = [UIColor whiteColor];
    refreshLabel.shadowOffset = CGSizeMake(0, 1);
    
    
    refreshLastUpdateTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 32, 250, 13)];
    refreshLastUpdateTimeLabel.backgroundColor = [UIColor clearColor];
    refreshLastUpdateTimeLabel.font = [UIFont systemFontOfSize:11];
    refreshLastUpdateTimeLabel.textColor = [UIColor colorWithHex:0x666666];
    refreshLastUpdateTimeLabel.shadowColor = [UIColor whiteColor];
    refreshLastUpdateTimeLabel.shadowOffset = CGSizeMake(0, 1);
    
    refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list_pulldown"]];
    refreshArrow.frame = CGRectMake(18, 22, 19, 23);
    
    refreshSpinner = [[LoadingView alloc] initWithFrame:CGRectMake(9, 5, 44, 44)];
    
    [self addSubview:refreshLabel];
    [self addSubview:refreshLastUpdateTimeLabel];
    [self addSubview:refreshArrow];
    [self addSubview:refreshSpinner];
}

- (void)startLoading {
    isLoading = YES;
    
    // Show the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    refreshLabel.text = @"목록을 업데이트 중입니다.";
    refreshArrow.hidden = YES;
    
    [self showLastUpdateDateTimeLabel];
    
    [refreshSpinner startAnimating];
    [UIView commitAnimations];
    
    // Refresh action!
    [self refresh];
}

- (void)stopLoading {
    isLoading = NO;
    
    // Hide the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDidStopSelector:@selector(stopLoadingComplete:finished:context:)];
    
    [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
    [UIView commitAnimations];
}

- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    // Reset the header
    refreshLabel.text = @"아래로 당기시면 목록을 업데이트 합니다.";
    refreshArrow.hidden = NO;
    [refreshSpinner stopAnimating];
}

- (void)refresh {
    [[ListCommunicator sharedInstance] requestFlowerList:self action:@selector(updateListReceiveResult:) isUserInteraction:YES];
    //[[ListCommunicator sharedInstance] requestFlowerList];
    isNetworkLoading = YES;
}


- (void)rearrangePullUpRefreshView:(NSInteger)dataCount
{
    if (!refreshFooterView)
    {
        refreshFooterView = [[UIView alloc] init];
        refreshFooterView.backgroundColor = [UIColor clearColor];
        
        refreshFooterLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, refreshHeaderHeight)];
        refreshFooterLabel.backgroundColor = [UIColor clearColor];
        refreshFooterLabel.font = [UIFont boldSystemFontOfSize:12.0];
        refreshFooterLabel.textAlignment = NSTextAlignmentCenter;
        
        refreshFooterArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
        refreshFooterArrow.frame = CGRectMake(floorf((refreshHeaderHeight - 27) / 2),
                                              (floorf(refreshHeaderHeight - 44) / 2),
                                              27, 44);
        
        refreshFooterSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        refreshFooterSpinner.frame = CGRectMake(floorf(floorf(refreshHeaderHeight - 20) / 2), floorf((refreshHeaderHeight - 20) / 2), 20, 20);
        refreshFooterSpinner.hidesWhenStopped = YES;
        
        [refreshFooterView addSubview:refreshFooterLabel];
        [refreshFooterView addSubview:refreshFooterArrow];
        [refreshFooterView addSubview:refreshFooterSpinner];
        [self addSubview:refreshFooterView];
    }
}


/**
 pull down refresh 영역에 마지막 업데이트 일시를 표시한다.
 */
- (void)showLastUpdateDateTimeLabel
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSDate * lastUpdateDateTime = (NSDate *)[ud objectForKey:LAST_LIST_UPDATE_TIME];
    
    NSDateFormatter *ymdFormatter = [[NSDateFormatter alloc] init];
    [ymdFormatter setLocale:[NSLocale currentLocale]];
    [ymdFormatter setDateFormat:@"yy/MM/dd a hh:mm"];
    NSString *lastUpdateDateTimeString = [ymdFormatter stringFromDate:lastUpdateDateTime];
    
    NSLog(@"%@", lastUpdateDateTimeString);
    if ([lastUpdateDateTimeString isEqual:[NSNull null]] || ![lastUpdateDateTimeString length]) {
        lastUpdateDateTimeString = @"첫번째 업데이트입니다.";
    }
    refreshLastUpdateTimeLabel.text = [NSString stringWithFormat:@"마지막 업데이트 : %@", lastUpdateDateTimeString];
    [ud setObject:lastUpdateDateTime forKey:LAST_LIST_UPDATE_TIME];
    [ud synchronize];
}

#pragma mark -
- (void)updateListReceiveResult:(NSNumber*)result {
    //    NSLog(@"%s", __func__);
    
    isNetworkLoading = NO;
    BOOL isSuccess = [result boolValue];
    
    if (isSuccess && !isRequestCancel)
    {
        if(delegate != nil && [(id)delegate respondsToSelector:@selector(finishLoad)]) {
            [delegate finishLoad];
        }
    }

    // pull down refresh 기능에 의해 목록을 업데이트 한 경우 stop logic
    if (isLoading)
    {
        [self stopLoading];
    }
}

- (BOOL)isLoading {
    return isLoading;
}

- (void)setRefreshViewLabel:(int)type {
    if(type == 1) {
        // User is scrolling above the header
        refreshLabel.text = @"목록이 업데이트 됩니다.";
        [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
    }
    else {
        refreshLabel.text = @"아래로 당기시면 목록을 업데이트 합니다.";
        [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
        
        [self showLastUpdateDateTimeLabel];
    }
}

@end
